Skip to content

In Data Loading, Clip to Layer BoundingBox (Redo #8551) #8573

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
May 12, 2025

Conversation

MichaelBuessemeyer
Copy link
Contributor

@MichaelBuessemeyer MichaelBuessemeyer commented Apr 28, 2025

2nd iteration of #8551

Additionally, the nullable DataSource in various data request classes was replaced by Option[DataSourceId] to avoid Null exceptions in this context in the future.

Steps to test:

  • Edit the datasource-properties.json of an existing dataset to have a smaller bounding box than the existing data on disk
  • When viewing the dataset (after cache clear), the loaded data for that layer should be clipped accordingly
  • Zoom out to test different mags
  • Test that volume annotating works even if you touch the bounding box dataset (data should still be there after reload)
  • Test that for both on-disk segmentations and volume annotations, and proofreading, data loading and ad-hoc meshing still works.

Issues:


  • Updated changelog
  • Removed dev-only changes like prints and application.conf edits
  • Considered common edge cases
  • Needs datastore update after deployment

Copy link
Contributor

coderabbitai bot commented Apr 28, 2025

📝 Walkthrough

Walkthrough

This change refactors data source handling to use identifiers instead of full objects, introduces explicit bounding box clipping for data layers, and improves geometry utilities. Data outside a layer's bounding box is now zeroed out during loading, ensuring correct cropping. The update also replaces nulls with None for optionals and modernizes vector negation.

Changes

Files/Paths (grouped) Change Summary
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/BinaryDataService.scala Adds bounding box clipping for data outside the valid region, introduces the clipToLayerBoundingBox method, and refactors data source references to use IDs.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/DataServiceRequests.scala Refactors request models to use DataSourceId/Option[DataSourceId] instead of DataSource, adds dummy ID helpers, and exposes cuboid magnitude.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/controllers/BinaryDataController.scala,
webknossos-datastore/app/com/scalableminds/webknossos/datastore/controllers/ZarrStreamingController.scala,
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/FindDataService.scala,
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/MappingService.scala,
webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/SegmentIndexFileService.scala
Refactors all usages to pass data source identifiers instead of full objects, updating method signatures and internal calls accordingly.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/dataformats/DatasetArrayBucketProvider.scala,
webknossos-datastore/app/com/scalableminds/webknossos/datastore/dataformats/MappingProvider.scala
Updates internal data source references from nested objects to direct IDs for path resolution and file access.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/storage/AgglomerateFileCache.scala,
webknossos-datastore/app/com/scalableminds/webknossos/datastore/storage/ParsedMappingCache.scala
Updates cache key and mapping construction to use new data source ID logic, including dummy IDs for volume tracings.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/datasource/DataSource.scala Simplifies DataSourceId.toString to return only the organization and directory name.
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/Cuboid.scala Adds conversion methods from Cuboid to BoundingBox in different coordinate magnitudes.
util/src/main/scala/com/scalableminds/util/geometry/BoundingBox.scala Makes bottomRight lazy, adds isFullyContainedIn and move methods for bounding boxes.
util/src/main/scala/com/scalableminds/util/geometry/Vec3Int.scala Replaces the negate method with the unary_- operator for vector negation.
webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/tracings/editablemapping/EditableMappingService.scala,
webknossos-tracingstore/app/com/scalableminds/webknossos/tracingstore/tracings/volume/VolumeTracingService.scala
Replaces null with None for optional data source IDs in request construction.
CHANGELOG.unreleased.md Documents the new behavior of zeroing out data outside bounding boxes during data loading.

Assessment against linked issues

Objective (Issue #) Addressed Explanation
Data outside bounding box should be zeroed/clipped (#5775)
Ensure backend clips/crops layer data at bounding box (#5775)

Suggested labels

backend, bug, refactoring

Suggested reviewers

  • MichaelBuessemeyer

Poem

In fields of code where data grows,
A bounding box the rabbit knows:
If bytes stray out, they're now set low,
Zeroed clean where crops must go.
With IDs neat and vectors spry,
The backend hops—no nulls nearby!
🐇✨

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@MichaelBuessemeyer MichaelBuessemeyer changed the title In Data Loading, Clip to Layer BoundingBox ( Redo #8551) In Data Loading, Clip to Layer BoundingBox (Redo #8551) Apr 28, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (4)
CHANGELOG.unreleased.md (1)

22-22: LGTM, but consider a minor language improvement.

Clearly explains the new behavior of zeroing out data outside the defined bounding box. The explanation is precise and matches the PR's objectives.

Consider simplifying "outside of the bounding box" to just "outside the bounding box" to avoid redundancy:

- When loading data from a data layer that has data stored beyond the bounding box specified in the datasource-properties.json, data outside of the bounding box is now zeroed. (the layer is "clipped"). [#8551](https://github.com/scalableminds/webknossos/pull/8551)
+ When loading data from a data layer that has data stored beyond the bounding box specified in the datasource-properties.json, data outside the bounding box is now zeroed. (the layer is "clipped"). [#8551](https://github.com/scalableminds/webknossos/pull/8551)
🧰 Tools
🪛 LanguageTool

[style] ~22-~22: This phrase is redundant. Consider using “outside”.
Context: ...in the datasource-properties.json, data outside of the bounding box is now zeroed. (the la...

(OUTSIDE_OF)

util/src/main/scala/com/scalableminds/util/geometry/BoundingBox.scala (2)

48-50: Avoid temporary allocation in isFullyContainedIn for a micro-performance win
intersection allocates a new BoundingBox just to compare against this.
For a hot path you can sidestep the allocation by comparing coordinates directly:

- def isFullyContainedIn(other: BoundingBox): Boolean =
-   this.intersection(other).contains(this)
+ def isFullyContainedIn(other: BoundingBox): Boolean =
+   topLeft.x >= other.topLeft.x &&
+   topLeft.y >= other.topLeft.y &&
+   topLeft.z >= other.topLeft.z &&
+   bottomRight.x <= other.bottomRight.x &&
+   bottomRight.y <= other.bottomRight.y &&
+   bottomRight.z <= other.bottomRight.z

This keeps the method allocation–free while preserving semantics.


67-69: Minor naming nitpick – consider translate instead of move
The new helper is great, but move now exists in both BoundingBox and Vec3Int with slightly different semantics (in-place vs. returning a new box). Using a verb like translate or shift would reduce cognitive load and avoid confusing it with the Vec3Int counterpart.

webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/BinaryDataService.scala (1)

111-139: clipToLayerBoundingBox copies row-wise but still triple-loops ‑ can be flattened
Great to see explicit clipping! The inner copy already works per X-row; you can also flatten Y/Z loops by computing linear slice offsets and invoking a single System.arraycopy per contiguous block.
This typically halves the loop overhead for large requests:

- for {
-   z <- intersection.topLeft.z until intersection.bottomRight.z
-   y <- intersection.topLeft.y until intersection.bottomRight.y
- } {
-   val offset = (intersection.topLeft.x +
-                 y * requestBboxInMag.width +
-                 z * requestBboxInMag.width * requestBboxInMag.height) * bytesPerElement
-   System.arraycopy(inputArray,
-                    offset,
-                    outputArray,
-                    offset,
-                    (intersection.bottomRight.x - intersection.topLeft.x) * bytesPerElement)
- }
+val rowBytes = (intersection.bottomRight.x - intersection.topLeft.x) * bytesPerElement
+val sliceBytes = requestBboxInMag.width * requestBboxInMag.height * bytesPerElement
+val yStride   = requestBboxInMag.width * bytesPerElement
+
+var z = intersection.topLeft.z
+while (z < intersection.bottomRight.z) {
+  var y = intersection.topLeft.y
+  val zOffset = z * sliceBytes
+  while (y < intersection.bottomRight.y) {
+    val offset = zOffset + y * yStride + intersection.topLeft.x * bytesPerElement
+    System.arraycopy(inputArray, offset, outputArray, offset, rowBytes)
+    y += 1
+  }
+  z += 1
+}

No change in behaviour, ~2-3× speed-up on large volumes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d30f8d8 and 0b77cdf.

📒 Files selected for processing (6)
  • CHANGELOG.unreleased.md (1 hunks)
  • util/src/main/scala/com/scalableminds/util/geometry/BoundingBox.scala (3 hunks)
  • util/src/main/scala/com/scalableminds/util/geometry/Vec3Int.scala (1 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/Cuboid.scala (2 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/DataServiceRequests.scala (2 hunks)
  • webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/BinaryDataService.scala (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/DataServiceRequests.scala (2)
util/src/main/scala/com/scalableminds/util/geometry/Vec3Int.scala (2)
  • Vec3Int (7-89)
  • Vec3Int (91-157)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/Cuboid.scala (1)
  • mag (46-46)
util/src/main/scala/com/scalableminds/util/geometry/BoundingBox.scala (1)
util/src/main/scala/com/scalableminds/util/geometry/Vec3Int.scala (3)
  • move (53-56)
  • move (56-59)
  • other (32-35)
🪛 LanguageTool
CHANGELOG.unreleased.md

[style] ~22-~22: This phrase is redundant. Consider using “outside”.
Context: ...in the datasource-properties.json, data outside of the bounding box is now zeroed. (the la...

(OUTSIDE_OF)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: build-smoketest-push
  • GitHub Check: backend-tests
  • GitHub Check: frontend-tests
🔇 Additional comments (7)
webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/DataServiceRequests.scala (2)

3-3: LGTM - Import correctly added.

The Vec3Int import is properly added to support the new mag method.


25-25: LGTM - Convenience accessor method.

This new method provides direct access to the cuboid's magnitude vector, consistent with the existing pattern of convenience methods like isSingleBucket. This will simplify code that needs to access the magnitude in data request processing.

util/src/main/scala/com/scalableminds/util/geometry/Vec3Int.scala (1)

26-28: LGTM - Good use of Scala's unary operator overloading.

Replacing a negate method with the unary minus operator unary_- is a good improvement. This follows idiomatic Scala by allowing the more natural syntax -vec instead of vec.negate(), making the code more readable and aligning with mathematical notation.

webknossos-datastore/app/com/scalableminds/webknossos/datastore/models/requests/Cuboid.scala (2)

3-3: LGTM - Import correctly added.

The BoundingBox import is properly added to support the new conversion methods.


55-59: LGTM - Well-implemented conversion methods.

The new methods provide useful conversions between Cuboid and BoundingBox representations, which are essential for the bounding box clipping functionality. The implementation is correct, using the appropriate magnitude-aware coordinates.

  • toBoundingBoxInMag creates a BoundingBox using the cuboid's top-left position in magnitude coordinates
  • toMag1BoundingBox leverages the existing toMag1 method to first normalize to mag1, then convert to a BoundingBox

These methods follow the naming pattern of existing conversion methods like toMag1.

webknossos-datastore/app/com/scalableminds/webknossos/datastore/services/BinaryDataService.scala (2)

143-148: Clipping before agglomerate / half-byte conversion is the right order – nice!
The guard !request.cuboid.toMag1BoundingBox.isFullyContainedIn(...) prevents an unnecessary copy when the request is already inside bounds, keeping the fast path untouched.


232-235: Variable extraction improves readability – LGTM
Deriving rx/ry/rz once clarifies the intent and removes the previous silent division by subsampling stride. Implementation and indexing logic remain correct.

@fm3 fm3 self-assigned this Apr 29, 2025
@fm3
Copy link
Member

fm3 commented Apr 29, 2025

@MichaelBuessemeyer I found the problem here. The DataSource was set to null in the request classes for volume tracings. That was always by design and we had null checks in many spots. But this variable is accessed in convertIfNecessary (which now also happens in the tracingstore’s BinaryDataService). I now went ahead and replaced this null hack with an Option, so that the scala type system will help us avoid such problems in the future. Could you please have a look at my latest changes when you have time? (No hurry)

As you opened this PR someone else will have to hit approve eventually, but I still think that you could review the content 😇

Copy link
Contributor Author

@MichaelBuessemeyer MichaelBuessemeyer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome, thanks for fixing this so fast 🎉

I found 2 things please find them below.

Would give this PR an approval but as I opened it myself that up to you :)

@MichaelBuessemeyer MichaelBuessemeyer requested a review from fm3 April 29, 2025 12:50
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
CHANGELOG.unreleased.md (2)

21-21: Use consistent quoting for UI elements
Consider using backticks around the Create Animation job name to follow the existing convention (e.g., backticks around View Modes in other entries).

Apply this diff:

- - Replaced fixed threshold of 40 meshes by a dynamic limit based on the number of triangles in the mesh for the "Create Animation" job. [#8588]
+ - Replaced fixed threshold of 40 meshes by a dynamic limit based on the number of triangles in the mesh for the `Create Animation` job. [#8588]

25-25: Refine phrasing and remove redundancy
The phrase “outside of the bounding box” is redundant per our style guide and the parentheses break sentence flow. Also replace curly quotes with straight quotes.

Apply this diff:

- - When loading data from a data layer that has data stored beyond the bounding box specified in the datasource-properties.json, data outside of the bounding box is now zeroed. (the layer is “clipped”). [#8551]
+ - When loading data from a data layer that has data stored beyond the bounding box specified in the datasource-properties.json, data outside the bounding box is now zeroed, clipping the layer. [#8551]
🧰 Tools
🪛 LanguageTool

[style] ~25-~25: This phrase is redundant. Consider using “outside”.
Context: ...in the datasource-properties.json, data outside of the bounding box is now zeroed. (the la...

(OUTSIDE_OF)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2baa0ff and 58e5cad.

📒 Files selected for processing (1)
  • CHANGELOG.unreleased.md (1 hunks)
🧰 Additional context used
🪛 LanguageTool
CHANGELOG.unreleased.md

[style] ~25-~25: This phrase is redundant. Consider using “outside”.
Context: ...in the datasource-properties.json, data outside of the bounding box is now zeroed. (the la...

(OUTSIDE_OF)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: frontend-tests
  • GitHub Check: build-smoketest-push
  • GitHub Check: backend-tests

@fm3 fm3 merged commit 6fa3d30 into master May 12, 2025
5 checks passed
@fm3 fm3 deleted the revert-8572-revert-clip-to-bbox branch May 12, 2025 08:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Layer should be clipped at bounding box
2 participants